from django.utils.dateparse import parse_datetime

from ReportManager.views.view import model_info_dict
from UserManager.models import User
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from ReportManager.serializers import *
import pandas as pd
from django.http import HttpResponse
from io import BytesIO


class SelfGetView(APIView):
    def post(self, request):
        # 判断user的group是不是 reviews
        # try:
        return self.get_reports(request)

    # except Exception as e:
    #     return Response({'error': 'Invalid data' + str(e)}, status=400)

    # except Exception as e:
    #     return Response({'error': 'Invalid data' + str(e)}, status=400)

    def get_reports(self, request):
        # 根据id返回TrainingReport
        result = {"score": 0}
        userscores = UserScore.objects.filter(account=request.user.username)
        userscores = self.filter_reports_by_time(request, userscores)
        for userscore in userscores:
            result['score'] += userscore.score

        result = {"score": result["score"]}
        return Response(result, status=200)

    def filter_reports_by_time(self, request, userscores):
        start_time = request.data.get('start_time')
        end_time = request.data.get('end_time')
        if not start_time or not end_time:
            return Response({"error": "请提供 start_time 和 end_time 参数"}, status=status.HTTP_400_BAD_REQUEST)
            # 将字符串时间转换为 Python datetime 对象
        start_time = parse_datetime(start_time)
        end_time = parse_datetime(end_time)

        # 应用时间范围过滤
        userscores = userscores.filter(created_time__range=(start_time, end_time))

        return userscores


class AllGetView(APIView):
    def post(self, request):
        # 判断user的group是不是 reviews
        # try:
        if request.user.groups.filter(name='reviewer').exists() or request.user.groups.filter(
                name='TDAdmin').exists() or request.user.is_superuser:
            return self.get_reports(request)
        else:
            return Response({'error': '你没有权限访问这个api'}, status=403)

    def get_reports(self, request):
        # 根据id返回TrainingReport
        accounts = request.data.get('accounts')
        results = []
        if accounts is None:
            users = User.objects.all()
        else:
            users = User.objects.filter(username__in=accounts)
        for user in users:
            result = {'account': user.username, 'name': user.name, "score": 0}
            for key in model_info_dict.keys():
                result[model_info_dict[key]["model_name"]] = 0
            userscores = UserScore.objects.filter(account=user.username)
            userscores = self.filter_reports_by_time(request, userscores)
            userscores = list(userscores)
            if len(userscores) != 0:
                for userscore in userscores:
                    report_type = model_info_dict[userscore.report_type]["model_name"]
                    result[report_type] += userscore.score
                    result['score'] += userscore.score
            results.append(result)

        return Response(results, status=200)

    def filter_reports_by_time(self, request, userscores):
        start_time = request.data.get('start_time')
        end_time = request.data.get('end_time')
        if not start_time or not end_time:
            return Response({"error": "请提供 start_time 和 end_time 参数"}, status=status.HTTP_400_BAD_REQUEST)
            # 将字符串时间转换为 Python datetime 对象
        start_time = parse_datetime(start_time)
        end_time = parse_datetime(end_time)

        # 应用时间范围过滤
        userscores = userscores.filter(created_time__range=(start_time, end_time))

        return userscores


class AllGetFileView(APIView):
    def post(self, request):
        # 判断user的group是不是 reviews
        # try:
        if request.user.groups.filter(name='reviewer').exists() or request.user.groups.filter(
                name='TDAdmin').exists() or request.user.is_superuser:
            resdic = self.get_resultdic(request)
            # 将该字典转为excel文件
            # 直接将列表转换为DataFrame
            df = pd.DataFrame(resdic)

            # 创建一个BytesIO对象用来保存Excel文件的内容
            excel_file = BytesIO()

            # 将DataFrame写入Excel文件
            df.to_excel(excel_file, index=False)  # index=False表示不写入索引

            # 设置HttpResponse的类型和编码
            response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
            response['Content-Disposition'] = 'attachment; filename="scores.xlsx"'  # 自定义下载文件名

            # 将Excel文件内容写入HttpResponse
            excel_file.seek(0)  # 回到文件开头
            response.write(excel_file.getvalue())

            return response

        else:
            return Response({'error': '你没有权限访问这个api'}, status=403)

    def get_resultdic(self, request):

        # 根据id返回TrainingReport
        accounts = request.data.get('accounts')
        results = []
        if accounts is None:
            users = User.objects.all()
        else:
            users = User.objects.filter(username__in=accounts)
        for user in users:
            result = {'account': user.username, 'name': user.name, "score": 0}
            for key in model_info_dict.keys():
                result[model_info_dict[key]["model_name"]] = 0
            userscores = UserScore.objects.filter(account=user.username)
            userscores = self.filter_reports_by_time(request, userscores)
            # 如果userscores为空则无法迭代码
            userscores = list(userscores)
            if len(userscores) != 0:
                for userscore in userscores:
                    report_type = model_info_dict[userscore.report_type]["model_name"]
                    result[report_type] += userscore.score
                    result['score'] += userscore.score
            results.append(result)

        return results

    def filter_reports_by_time(self, request, userscores):
        start_time = request.data.get('start_time')
        end_time = request.data.get('end_time')
        if not start_time or not end_time:
            return Response({"error": "请提供 start_time 和 end_time 参数"}, status=status.HTTP_400_BAD_REQUEST)
            # 将字符串时间转换为 Python datetime 对象
        start_time = parse_datetime(start_time)
        end_time = parse_datetime(end_time)

        # 应用时间范围过滤
        userscores = userscores.filter(created_time__range=(start_time, end_time))

        return userscores
